#include "Precompile.h"
#include "SoundSystemOpenAL.h"

namespace Sound{
	SoundSystemOpenAL::SoundSystemOpenAL(){
		if(!initialize()){
			LOG_ERROR("Unable to initialize sound system.");
			assert(0);
		}
	}

	SoundSystemOpenAL::~SoundSystemOpenAL(){
		finalize();
	}

	void SoundSystemOpenAL::loadSoundDB(std::string folder){
		std::vector<std::string> filenames = Core::GeneralSettings::getFilesInFolder(folder);

		// Load sound files
	}

	bool SoundSystemOpenAL::update(){
		return true;
	}

	bool SoundSystemOpenAL::initialize(){
		ALDeviceList *pDeviceList = NULL;
		ALint i;
		ALboolean bReturn = AL_FALSE;

		pDeviceList = new ALDeviceList();
		if ((pDeviceList) && (pDeviceList->GetNumDevices()))
		{
			if(pDeviceList->GetNumDevices() <= 0){
				LOG_ERROR("No sound device found.");
				assert(0);
				delete pDeviceList;
				return false;
			}

			// Use first device
			i = 1;

			m_soundDevice = alcOpenDevice(pDeviceList->GetDeviceName(i - 1));
			if (m_soundDevice)
			{
				m_soundContext = alcCreateContext(m_soundDevice, NULL);
				if (m_soundContext)
				{
					alcMakeContextCurrent(m_soundContext);
					bReturn = AL_TRUE;
				}
				else
				{
					alcCloseDevice(m_soundDevice);
				}
			}

			delete pDeviceList;
		}

		if(bReturn != AL_FALSE)
			return true;
		return false;
	}

	void SoundSystemOpenAL::finalize(){
		ALCcontext *pContext;
		ALCdevice *pDevice;

		pContext = alcGetCurrentContext();
		pDevice = alcGetContextsDevice(pContext);
	
		alcMakeContextCurrent(NULL);
		alcDestroyContext(pContext);
		alcCloseDevice(pDevice);
	}
}